package com.SmartCare.service.impl;

import com.SmartCare.schedule.CallNoteScheduleTask;
import com.SmartCare.utils.CronTools;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.SmartCare.common.enums.Constants;
import com.SmartCare.common.Result;
import com.SmartCare.service.CallNoteService;
import com.SmartCare.common.vo.CallNoteVo;
import com.SmartCare.pojo.reminder.CallNote;
import com.SmartCare.mapper.CallNoteMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static java.lang.String.*;

/**
 * 通话提醒 服务实现类
 */
@Service
public class CallNoteServiceImpl extends ServiceImpl<CallNoteMapper, CallNote> implements CallNoteService {

    @Resource
    private CallNoteScheduleTask callNoteScheduleTask;

    /**
     * 查询通话提醒信息
     */
    @Override
    public Result queryAll(Long userId) {
        LambdaQueryWrapper<CallNote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CallNote::getFamilyMemberId, userId); //18l
        queryWrapper.orderByDesc(CallNote::getCreatedTime);
        List<CallNote> list = list(queryWrapper);

        List<CallNoteVo> listVo = new ArrayList<>();
        for (CallNote item : list) {
            CallNoteVo callNoteVo = new CallNoteVo();
            BeanUtils.copyProperties(item, callNoteVo);
            String corn = item.getNotificationTime();

            callNoteVo.setMinute(CronTools.extractMinute(corn));
            callNoteVo.setHour(CronTools.extractHour(corn));
            callNoteVo.setDayOfWeek(CronTools.extractDayOfWeek(corn));

            callNoteVo.setReminderContent(item.getReminderContent());

            listVo.add(callNoteVo);
        }
        return Result.success(listVo);
    }


    @Override
    public Result delete(List<Long> ids) {
        if (ids.size() == 0) {
            return Result.error("删除失败");
        }
        LambdaQueryWrapper<CallNote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CallNote::getId, ids);

        boolean removed = remove(queryWrapper);
        if (removed) {
            for (Long id : ids) {
                //逐个取消定时任务
                callNoteScheduleTask.cancelScheduledTask(id);
            }
            return Result.success("删除成功");
        }
        return Result.error(Constants.UNKNOWN_ERROR, "删除失败");
    }

    @Override
    public Result updateData(Long id, Integer second, int minuteValue, Integer hour, String dayOfMonth, String month, Integer dayOfWeek, String reminderContent, Integer status) {
        if (id == null) {
            return Result.error();
        }
        LambdaUpdateWrapper<CallNote> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(CallNote::getId, id);
        if (status != null) {
            updateWrapper.set(CallNote::getStatus, status);
        }

        if (reminderContent != null && !reminderContent.isEmpty()) {
            updateWrapper.set(CallNote::getReminderContent, reminderContent);
        }
        if (hour != null && dayOfWeek != null) {
            String cron = String.format("%d %d %d %s %s %d", second, minuteValue, hour, dayOfMonth, month, dayOfWeek);
            updateWrapper.set(CallNote::getNotificationTime, cron);
        }

        boolean result = update(updateWrapper);

        if (result) {
            //更新定时任务（先取消再添加）
            CallNote callNote = getById(id);
            callNoteScheduleTask.cancelScheduledTask(id);
            callNoteScheduleTask.addScheduledTask(callNote);
            return Result.success("修改成功");
        } else {
            return Result.error();
        }
    }

    @Override
    public Result addAlarm(Long userId, int second, int minute, int hour, int dayOfWeek, String month, String dayOfMonth, String reminderContent, int status) {
        // 构建cron表达式 0 0 8 ? * 2
        String cronExpression = format("%d %d %d %s %s %d", second, minute, hour, dayOfMonth, month, dayOfWeek);

        LambdaQueryWrapper<CallNote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CallNote::getFamilyMemberId, userId);
        queryWrapper.eq(CallNote::getNotificationTime, cronExpression);
        CallNote one = getOne(queryWrapper);

        if (one != null) {
            return Result.error("重复添加");
        }

        CallNote callNote = CallNote.builder()
                .familyMemberId(userId)
                .notificationTime(cronExpression)
                .reminderContent(reminderContent)
                .status(status)
                .build();

        boolean res = save(callNote);
        if (res) {
            //添加定时任务
            callNoteScheduleTask.addScheduledTask(callNote);
            return Result.success("修改成功");
        } else {
            return Result.error();
        }
    }

}
